﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using Monkey.Warrenty.Data.Interfaces;
using Monkey.Warrenty.EntityModel;

namespace Monkey.Warrenty.Data
{
    public class ProductGroupDao : IProductGroupDao
    {
        public List<ProductGroup> GetAllProductGroups()
        {
            List<ProductGroup> productGroups;

            using (var context = new MonkeyWarrantyEntities())
            {
                productGroups = context.ProductGroups.OrderBy(x => x.Name).ToList();
            }

            return productGroups;
        }

        public ProductGroup AddProductGroup(ProductGroup productGroup)
        {
            using (var context = new MonkeyWarrantyEntities())
            {
                context.ProductGroups.AddObject(productGroup);
                context.SaveChanges();
            }

            return productGroup;
        }

        public void UpdateProductGroup(ProductGroup productGroup)
        {
            // throw new System.NotImplementedException();
            if (productGroup == null || productGroup.Id == 0) return;

            using (var context = new MonkeyWarrantyEntities())
            {
                context.ProductGroups.Attach(productGroup);
                context.ObjectStateManager.ChangeObjectState(productGroup, EntityState.Modified);
                context.SaveChanges();
            }
        }

        public void DeleteProductGroup(int productGroupId)
        {
            if (productGroupId <= 0) return;
            using (var context = new MonkeyWarrantyEntities())
            {
                var productGroup = context.ProductGroups.First(g => g.Id == productGroupId);

                context.DeleteObject(productGroup);

                context.SaveChanges();
            }
        }

        public int GetMaxId()
        {
            var maxId = 0;

            using (var context = new MonkeyWarrantyEntities())
            {
                var productGroup = context.ProductGroups.OrderByDescending(x => x.Id).FirstOrDefault();
                if (productGroup != null) maxId = productGroup.Id;
            }

            return maxId;
        }

        public int GetCurrentIdentity()
        {
            long? identity;
            using (var context = new MonkeyWarrantyEntities())
            {
                identity = context.GetIdentity("ProductGroups").SingleOrDefault();
            }

            return identity.HasValue ? (int)identity.Value : 0;
        }

        public ProductGroup GetById(int id)
        {
            using (var context = new MonkeyWarrantyEntities())
            {
                return context.ProductGroups.FirstOrDefault(x => x.Id == id);
            }
        }
    }
}
